import { createApp } from 'vue'
import { createPinia } from 'pinia'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import 'element-plus/theme-chalk/dark/css-vars.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

import App from './App.vue'
import router from './router'
import './assets/styles/main.scss'
import './utils/errorHandler.js'  // 导入错误处理工具

const app = createApp(App)

// 注册所有Element Plus图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

app.use(createPinia())
app.use(router)
app.use(ElementPlus)

// 处理控制台警告和错误信息
if (typeof window !== 'undefined') {
  // 过滤console.error中的ARIA警告
  const originalConsoleError = console.error
  console.error = (...args) => {
    const message = args[0]
    if (typeof message === 'string') {
      // 忽略Element Plus组件的aria-hidden错误警告
      if (message.includes('Blocked aria-hidden') &&
          message.includes('descendant retained focus')) {
        return
      }
      // 忽略更广泛的ARIA相关警告
      if (message.includes('aria-hidden') &&
          (message.includes('retained focus') ||
           message.includes('assistive technology') ||
           message.includes('el-popper'))) {
        return
      }
      // 忽略Element Plus菜单相关警告
      if (message.includes('el-menu-item') &&
          message.includes('aria-hidden')) {
        return
      }
      // 忽略ECharts DOM尺寸警告
      if (message.includes('ECharts') &&
          (message.includes('Can\'t get DOM width or height') ||
           message.includes('clientWidth') ||
           message.includes('clientHeight') ||
           message.includes('Please check dom.clientWidth and dom.clientHeight') ||
           message.includes('They should not be 0'))) {
        return
      }
    }
    originalConsoleError.apply(console, args)
  }

  // 统一的警告过滤
  const originalConsoleWarn = console.warn
  console.warn = (...args) => {
    const message = args[0]
    if (typeof message === 'string') {
      // 忽略Sass弃用警告
      if (message.includes('DEPRECATION WARNING') &&
          message.includes('legacy-js-api')) {
        return
      }
      // 忽略CJS弃用警告
      if (message.includes('The CJS build of Vite') &&
          message.includes('deprecated')) {
        return
      }
      // 忽略构建工具相关警告
      if (message.includes('VITE') &&
          (message.includes('deprecated') || message.includes('warning'))) {
        return
      }
      // 忽略ARIA-hidden警告
      if (message.includes('aria-hidden') &&
          message.includes('descendant retained focus')) {
        return
      }
    }
    originalConsoleWarn.apply(console, args)
  }

  // 拦截并过滤浏览器开发者工具的警告
  const originalLog = console.log
  console.log = (...args) => {
    const message = args[0]
    if (typeof message === 'string') {
      // 过滤一些开发者工具的额外警告
      if (message.includes('Blocked aria-hidden') &&
          message.includes('el-menu-item')) {
        return
      }
    }
    originalLog.apply(console, args)
  }

  // 尝试拦截MutationEvent来阻止某些警告的触发
  if (typeof MutationObserver !== 'undefined') {
    const originalObserver = MutationObserver
    MutationObserver = function(callback) {
      const wrappedCallback = function(mutations, observer) {
        // 过滤掉与aria-hidden相关的mutation
        const filteredMutations = mutations.filter(mutation => {
          if (mutation.type === 'attributes' &&
              mutation.attributeName === 'aria-hidden') {
            // 检查是否是Element Plus的popper元素
            const target = mutation.target
            if (target.classList &&
                (target.classList.contains('el-popper') ||
                 target.getAttribute('role') === 'tooltip')) {
              return false
            }
          }
          return true
        })

        if (filteredMutations.length > 0) {
          callback(filteredMutations, observer)
        }
      }
      return new originalObserver(wrappedCallback)
    }
  }
}

app.mount('#app')

// 额外的ARIA警告预防措施
if (typeof window !== 'undefined') {
  // 等待DOM加载完成后处理Element Plus的popper元素
  setTimeout(() => {
    // 监听DOM变化，提前处理可能产生ARIA警告的元素
    const observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        if (mutation.type === 'childList') {
          mutation.addedNodes.forEach((node) => {
            if (node.nodeType === Node.ELEMENT_NODE) {
              // 查找所有el-popper元素
              const poppers = node.classList?.contains('el-popper')
                ? [node]
                : node.querySelectorAll?.('.el-popper') || []

              poppers.forEach(popper => {
                // 在设置aria-hidden之前，先移除焦点
                if (popper.getAttribute('aria-hidden') === 'true') {
                  const focusedElement = popper.querySelector(':focus')
                  if (focusedElement) {
                    focusedElement.blur()
                  }
                }
              })
            }
          })
        }

        if (mutation.type === 'attributes' && mutation.attributeName === 'aria-hidden') {
          const target = mutation.target
          if (target.classList?.contains('el-popper') &&
              target.getAttribute('aria-hidden') === 'true') {
            // 移除任何可能获得焦点的子元素的焦点
            const focusableElements = target.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')
            focusableElements.forEach(el => el.blur())
          }
        }
      })
    })

    // 观察整个document的变化
    observer.observe(document.body, {
      childList: true,
      subtree: true,
      attributes: true,
      attributeFilter: ['aria-hidden']
    })

    // 立即处理现有的popper元素
    const existingPoppers = document.querySelectorAll('.el-popper')
    existingPoppers.forEach(popper => {
      if (popper.getAttribute('aria-hidden') === 'true') {
        const focusableElements = popper.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')
        focusableElements.forEach(el => el.blur())
      }
    })
  }, 1000) // 延迟1秒执行，确保Element Plus组件已初始化
}